﻿using System;
using System.Data;
using System.Data.SqlServerCe;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Home.Mobilesales.Common;
using Home.MobileSales.Common.Entities;

namespace Home.MobileSales.Common.Models
{
    public class RemainingRepository
    {
        public void UpdateRemaining (Remaining remaining)
        {
            using (SqlCeConnection connection = WorkDataBase.CreateConnection())
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();
                string sqlQuery =
                    "UPDATE Remains "+
                    "SET Quantity = @Quantity "+
                    "Where SkladId = @SkladId and GoodId = @GoodId";
                using (SqlCeCommand com = new SqlCeCommand(sqlQuery, connection))
                {
                    com.Parameters.Add("@Quantity", remaining.Quantity);
                    com.Parameters.Add("@SkladId", remaining.SkladId);
                    com.Parameters.Add("@GoodId", remaining.GoodId);

                    if (com.ExecuteNonQuery() < 1)
                    {
                        throw new OtherException("Не змінено жодного запису");
                    }
                }
            }
            
        }

        public Remaining GetRemainingById(int skladId, int goodId)
        {
            using (SqlCeConnection connection = WorkDataBase.CreateConnection())
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();
                string sqlQuery = "Select Quantity, SkladId, GoodId " +
                                  "from Remains " +
                                  "where SkladId = @SkladId and GoodId = GoodId";
                using (SqlCeCommand com = new SqlCeCommand(sqlQuery, connection))
                {
                    com.Parameters.Add("@SkladId", skladId);
                    com.Parameters.Add("@GoodId", goodId);
                    using (SqlCeDataReader dr = com.ExecuteReader())
                    {
                        int goodIdCol = dr.GetOrdinal("GoodId");
                        int skladIdCol = dr.GetOrdinal("SkladId");
                        int quantityCol = dr.GetOrdinal("Quantity");
                        if (dr.Read())
                        {
                            Remaining rem = new Remaining();
                            rem.GoodId = dr.GetInt32(goodIdCol);
                            rem.SkladId = dr.GetInt32(skladIdCol);
                            rem.Quantity = dr.GetDouble(quantityCol);
                            return rem;
                        }
                        return null;
                    }
                }

            }
        }

    }
}
